package com.nclg.exam.controller;

import com.nclg.exam.dto.LoginDto;
import com.nclg.exam.entity.TUser;
import com.nclg.exam.service.UserService;
import com.nclg.exam.utils.JsonResult;
import com.nclg.exam.utils.MD5Utils;
import com.nclg.exam.utils.MailUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * ajax用户登录
     * @param loginDto
     * @param bindingResult
     * @return
     */
    @PostMapping("/login")
    public JsonResult login(@Valid LoginDto loginDto, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            return JsonResult.failure(msg);
        }

        //1、获取到subject对象
        Subject subject = SecurityUtils.getSubject();
        //2、封装token 令牌，传入前台输入的用户名，密码
        UsernamePasswordToken token = new UsernamePasswordToken(loginDto.getUAccount(), loginDto.getUPassword());
        //3、执行登录操作
        try {
            subject.login(token);
            TUser user = (TUser) subject.getPrincipal();
            //如果用户在数据库中status字段为1，表示启用状态，允许登录
            if ("1".equals(user.getUStatus())){
                return JsonResult.success("登录成功"); //1 - 200
            } else {
                //status字段为0，表示禁用状态，不允许登录
                subject.logout();
                return JsonResult.failure("该用户未被启用"); //0 - 500
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failure("用户名或密码错误");
        }

    }

    /**
     * 注册用户
     * @param tUser
     * @param code
     * @param request
     * @return
     */
    @PostMapping("/register")
    public JsonResult register(TUser tUser, String code, HttpServletRequest request){
        String idcode = (String) request.getSession().getAttribute("idcode");
        if (null == idcode || idcode.isEmpty()) return JsonResult.failure("您未发送验证码");
        if (idcode.equals(code)){
            Map<String, String> map = MD5Utils.md5(tUser.getUPassword());
            tUser.setUPassword(map.get("password"));
            tUser.setUSalt(map.get("salt"));
            tUser.setUIco("/static/images/ico/头像2.png");
            if (userService.insertSelective(tUser)) {
                return JsonResult.success("注册成功，正在跳转登录页面");
            }
        }
        return JsonResult.failure("注册失败");
    }

    /**
     * 发送邮箱验证码
     * @param mail
     * @param response
     * @param request
     * @return
     */
    @GetMapping("/sendIdCode/{mail}")
    public JsonResult sendIdCode(@PathVariable String mail, HttpServletResponse response, HttpServletRequest request){
        response.setCharacterEncoding("utf-8");
        //获取验证码
        String code = MailUtils.getCode();
        StringBuilder builder = new StringBuilder();
        builder.append("尊敬的" + mail + " 【先生/女士】:欢迎注册！您的验证码是：" + code
                + " ，仅用于本网站会员注册激活,请勿告知他人【在线考试管理系统】。");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        builder.append("\n时间: " + dateFormat.format(new Date()));
        try {
            MailUtils.sendMail(mail, builder.toString());
            request.getSession().setAttribute("idcode", code);
            return JsonResult.success("验证码已发送");
        } catch (MessagingException e) {
            e.printStackTrace();
            return JsonResult.failure("验证码发送失败");
        }
    }
}
